package com.gdth.bank.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.AppCompatSpinner;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import com.gdth.bank.BankApplication;
import com.gdth.bank.R;
import com.gdth.bank.adapter.CjkhListViewAdapter;
import com.gdth.bank.adapter.CjkhListViewAdapter.OnCjjlDetailClickListener;
import com.gdth.bank.bean.CjkhItem;
import com.gdth.bank.event.CjkhjlListEvent;
import com.gdth.bank.model.SynchronizeModel;
import com.gdth.bank.presenter.CjkhjlListPresenter;
import com.gdth.bank.service.CjkhjlService;
import com.gdth.bank.utils.AppUtil;
import com.gdth.bank.view.CjkhjlListView;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseActivity;
import com.gdth.database.bean.TAppBfrjJbxxb;
import com.gdth.database.bean.TAppYh;
import com.gdth.thread.SynchronizeThread;
import com.gdth.utils.DateTimeUtil;
import com.gdth.utils.GsonUtil;
import com.gdth.utils.ToolUtil;
import com.gdth.widget.dialog.BaseToast;
import com.gdth.widget.dialog.DialogConfig;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.Mode;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.google.gson.Gson;
import com.gdth.widget.pulltorefresh.library.PullToRefreshListView;

/**
 * 采集客户记录列表页面
 * 
 * @author arvin
 * 
 */
public class CjkhjlListActivity extends BaseActivity implements CjkhjlListView {
	@ViewInject(id = R.id.header_label_title)
	TextView txt_header_title;
	@ViewInject(id = R.id.header_btn_left, click = "finishClick")
	TextView txt_header_left;
	@ViewInject(id = R.id.header_btn_right, click = "addClick")
	TextView txt_header_right;
	@ViewInject(id = R.id.cjkhjl_query, click = "queryClick")
	TextView txt_query;
	@ViewInject(id = R.id.editTextNote)
	EditText edit_query;
	Button shangyiye;
	Button xiayiye;
	Spinner dangqianye;

	@ViewInject(id = R.id.listView)
	PullToRefreshListView listView;

	ListView mListView;

	CjkhjlListPresenter mCjkhjlPresenter;

	CjkhListViewAdapter mAdapter;
	List<CjkhItem> listData;

	/** 查询要素 **/
	String queryVal;

	/** 查询要素 **/
	Date queryDate;

	/** 提示框 */
	private ProgressDialog mProgressDialog;

	public TAppYh user;

	public boolean isRefresh = true;

	private int pagernumber = 0;
	private int allPager = 1;
	private int allNumber = 1;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cjkhjl_list);
		EventBus.getDefault().register(this);
		user = BankApplication.mInstance.getCurrentUser();
		dangqianye = findViewById(R.id.dangqianye);
		xiayiye = findViewById(R.id.xiayiye);
		shangyiye =findViewById(R.id.shangyiye);
		mCjkhjlPresenter = new CjkhjlListPresenter(this);
		initView();
		shangyiye.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				shangyiye();
			}
		});
		xiayiye.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				xiayiye();
			}
		});
		for (int i = 0; i < 1; i++) {
			bflxListStr.add("第" + (i+ 1) + "页/" + "共" + allPager + "页");
		}
		initSpinner();
	}
	List<String> bflxListStr = new ArrayList<String>(); // 当前页数
	private ArrayAdapter<String> adapter;
	private void initSpinner() {
//		if(bflxListStr.size() != 0){
		adapter = new ArrayAdapter<String>(CjkhjlListActivity.this, R.layout.item_bflx_select, bflxListStr);
		adapter.setDropDownViewResource(R.layout.item_bflx_no_select);
		dangqianye.setAdapter(adapter);
//		}
		//dangqianye.setSelection(0,true);
		dangqianye.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				pagernumber = position;
				getDataList();
				//addVisitFragment.setbflx(bflxList.get(position).getKey(),bflxList.get(position).getValue());
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(isRefresh) {
			init();
			isRefresh = false;
		}
	}

	@SuppressLint("ResourceAsColor")
	private void initView() {
		txt_header_title.setText(getResources().getString(R.string.param111));
		mProgressDialog = new ProgressDialog(this);

		listData = new ArrayList<CjkhItem>();

		mAdapter = new CjkhListViewAdapter(this, listData);
		mAdapter.setOnCjjlDetailClickListener(new OnDetailClickListener()); // modify by pal 20120111 解决翻页后数据错乱问题

		mListView = listView.getRefreshableView();
		mListView.setDivider(new ColorDrawable(R.color.line_color));
		mListView.setDividerHeight(1);
		listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				if (refreshView.isHeaderShown()) {
					// 下拉刷新 业务代码
					query(1);
				} else {
					listView.onRefreshComplete();
					// 上拉加载更多 业务代码
					// xjc --- 对于数据越界2019-5-28
//					if (listData.size() != 0) {
//						CjkhItem item = listData.get(listData.size() - 1);
//						queryDate = item.getCjsj();
//						query(2);
//					} else {
//						// 2019 -6 -13 xjc
//						listView.onRefreshComplete();
//						mAdapter.notifyDataSetChanged();
//						// CjkhItem item = listData.get(listData.size());
//						// queryDate = item.getCjsj();
//						// query(2);
//					}
				}
			}
		});

		listView.setMode(Mode.PULL_FROM_START);
		listView.setAdapter(mAdapter);
		/*
		 * modify by pal 20120111 解决翻页后数据错乱问题 listView.setOnItemClickListener(new
		 * OnItemClickListener() {
		 * 
		 * @Override public void onItemClick(AdapterView<?> parent, View view, int
		 * position, long id) { int po = position - 1; detail(po); } }); modify by pal
		 * 20120111 解决翻页后数据错乱问题 end
		 */
		listView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
			@Override
			public void onLastItemVisible() {
//				BaseToast.getInstance().ShowSystemToast(CjkhjlListActivity.this, getResources().getString(R.string.param112));
			}
		});
	}

	private void init() {
		query(1);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == AppUtil.activity_cjjl_requestcode && resultCode == AppUtil.activity_cjjl_resultcode) {
			query(1);
		} 
	}

	/**
	 * 长按菜单事件
	 * 
	 * @author arvin
	 * 
	 */
	class OnDetailClickListener implements OnCjjlDetailClickListener {
		@Override
		public void clickListener(int position) {
			detail(position);
		}
	}

	private void detail(int position) {
		CjkhItem item = listData.get(position);
		Intent intent = new Intent(CjkhjlListActivity.this, CjkhjlActivity.class);
		intent.putExtra("zjhm", item.getSfz());
		intent.putExtra("wybs", item.getKey());
		intent.putExtra("khxm", item.getValue());
		this.startActivity(intent);
	}

	public void addClick(View arg0) {
		Intent intent = new Intent(CjkhjlListActivity.this, CjkhxxActivity.class);
		intent.putExtra("type",0);
		this.startActivity(intent);
	}

	public void queryClick(View arg0) {
		queryVal = edit_query.getText().toString().trim();
//		query(1);
//		if(queryVal.equals("")){
//			BaseToast.getInstance().ShowCenterToast(this,"查询条件为空");
//			query(1);
//			return;
//		}
		queryDate = new Date();
		mCjkhjlPresenter.getqureAllCjkhxx(user.getZh(), queryVal, queryDate, 3);

	}

	private void query(int type) {
		if (type == 1)
			queryDate = new Date();

		if (queryVal == null)
			queryVal = "";

		String date = DateTimeUtil.getCurrentTime(queryDate, "yyyy-MM-dd HH:mm:ss");
		// this.showMessage(date);
		mCjkhjlPresenter.getAllCjkhxx(user.getZh(), "", queryDate, type);
	}

	@Override
	public void showProgressDialog(String msg) {
		// TODO Auto-generated method stub
		mProgressDialog.setMessage(msg);
		mProgressDialog.show();
	}

	@Override
	public void hideProgressDialog() {
		// TODO Auto-generated method stub
		mProgressDialog.hide();
	}

	@Override
	public void showMessage(String msg) {
		// TODO Auto-generated method stub
		try {
			Toast.makeText(CjkhjlListActivity.this, msg, Toast.LENGTH_SHORT).show();
		} catch (IllegalStateException e) {

		} catch (Exception e) {

		}

	}

	private void shangyiye(){
		try{
			if(pagernumber > 0){
				--pagernumber;
				dangqianye.setSelection(pagernumber,true);
			}
		}catch (IndexOutOfBoundsException e){

		}
//		getDataList();
	}

	private void xiayiye(){
		try{
			if(pagernumber < allPager){
				++pagernumber;
				dangqianye.setSelection(pagernumber,true);
			}
		}catch (IndexOutOfBoundsException e){

		}

//		getDataList();
	}

	public void getDataList(){
		List<TAppBfrjJbxxb> showdata = new ArrayList<>();
		int alldatasize = mListLocal.size();
		if(alldatasize <=10){
			showdata.addAll(mListLocal.subList(0,alldatasize ));
		}else if(alldatasize > 10){
			if((pagernumber+1)*10 < alldatasize){
				showdata.addAll(mListLocal.subList(pagernumber*10,(pagernumber+1)*10 ));
			}else {
				showdata.addAll(mListLocal.subList(pagernumber*10,alldatasize));
			}
		}

		listData.clear();
		for (TAppBfrjJbxxb mCjkhjl : showdata) {
			CjkhItem mImageItem = new CjkhItem();
			mImageItem.setKey(mCjkhjl.getUuid());
			mImageItem.setValue(mCjkhjl.getKhxm());
			mImageItem.setSfz(mCjkhjl.getZjhm());
			mImageItem.setCjsj(mCjkhjl.getCjsj());
			mImageItem.setTbzt(mCjkhjl.getSjzt());
			listData.add(mImageItem);
		}

		listView.onRefreshComplete();
		mAdapter.notifyDataSetChanged();
	}

	public List<TAppBfrjJbxxb> mListLocal = new ArrayList<>();
	public int AllListsize = 0;
	@Override
	public void refreshData(List<TAppBfrjJbxxb> mList) {
		mListLocal.clear();
		mListLocal.addAll(mList);
		AllListsize = mList.size();
		edit_query.setHint("姓名/身份证，共" + AllListsize + "人");
		getDataList();

		allPager = mList.size()/10;
		allPager ++;
		bflxListStr.clear();
		for (int i = 0; i < allPager; i++) {
			bflxListStr.add("第" + (i+ 1) + "页/" + "共" + allPager + "页");
		}
		initSpinner();
		//adapter.notifyDataSetChanged();
		//dangqianye.setSelection(0);
		showMessage("刷新成功");
	}
	@Override
	public void loadMoreData(List<TAppBfrjJbxxb> mList) {
//		for (TAppBfrjJbxxb mCjkhjl : mList) {
//			CjkhItem mImageItem = new CjkhItem();
//			mImageItem.setKey(mCjkhjl.getUuid());
//			mImageItem.setValue(mCjkhjl.getKhxm());
//			mImageItem.setSfz(mCjkhjl.getZjhm());
//			mImageItem.setCjsj(mCjkhjl.getCjsj());
//			mImageItem.setTbzt(mCjkhjl.getSjzt());
//			listData.add(mImageItem);
//		}
//
//		listView.onRefreshComplete();
//		mAdapter.notifyDataSetChanged();

//		showMessage(getResources().getString(R.string.param115));
	}
	
	@Subscribe(threadMode = ThreadMode.MAIN)
	public void getList(CjkhjlListEvent Event) {
		//query(1);
		switch (Event.getType()){
			case CjkhjlListEvent.refreshList:
				isRefresh = true;
				break;
			case CjkhjlListEvent.handUpload:
				upload(Event.getUuid());
				break;
			case CjkhjlListEvent.BFLB_DEL_CODE: //  时间: 2020/4/21 9:46 AM ,作者: xjc, 作用: 拜访删除
				DialogConfig config = new DialogConfig(this, "是否确定删除该客户", true, new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						mCjkhjlPresenter.delCjkhJbxxZt(Event.getUuid(),user.getSfz());
					}
				});
				config.show();
				break;
			case CjkhjlListEvent.BFLB_DEL_NET_SUC:
					mCjkhjlPresenter.delete(Event.getUuid());
				break;
			case CjkhjlListEvent.BFLB_CHANAGE_CODE:
				int position = Integer.valueOf(Event.getUuid());
				CjkhItem item = listData.get(position);
				Intent intent = new Intent(CjkhjlListActivity.this, CjkhxxActivity.class);
				intent.putExtra("type",1);
				intent.putExtra("uuid",item.getKey());
				intent.putExtra("khxm",item.getValue());
				intent.putExtra("sfz",item.getSfz());
				this.startActivity(intent);
				break;
		}
	}
	
	SynchronizeThread thread = new SynchronizeThread();
    
		private void start() {

			if(!thread.isAlive()) {
				if (thread != null) {
					thread = new SynchronizeThread();
				}
				thread.start();
			}
	}
	
	public void upload(String uuid) {
		String val = getOneCjkhxxByZt(uuid);
		final SynchronizeModel mSynchronizeModel = new SynchronizeModel();
		mSynchronizeModel.upLoadCjkhxx(val)
		.subscribeOn(Schedulers.io())
		.unsubscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread()) //AndroidSchedulers.mainThread()
		.subscribe(new Subscriber<String>(){
			
			@Override
			public void onCompleted() {
				// TODO Auto-generated method stub
				BaseToast.getInstance().ShowSystemToast(BankApplication.mInstance.getBaseContext(), getResources().getString(R.string.param113));
				
			}
			
			@Override
			public void onError(Throwable arg0) {
				// TODO Auto-generated method stub
				BaseToast.getInstance().ShowSystemToast(BankApplication.mInstance.getBaseContext(), getResources().getString(R.string.param114) + arg0);
			}
			
			@Override
			public void onNext(String arg0) {
				// TODO Auto-generated method stub
				mSynchronizeModel.UpdateZtForBfrj(arg0);
				// 延时刷新界面
				new Handler().postDelayed(new Runnable(){   
					public void run() {
							try {
								init();
							}catch(Exception e) {
								
							}
					    }   
					 }, 500); 
			}
			
		});
	}
	
	
	
	/**
	 * 根据状态获取需要更新的采集客户数据
	 * @return
	 */	
	public String getOneCjkhxxByZt(String uuid){
		CjkhjlService mCjkhjlService = new CjkhjlService();
		List<TAppBfrjJbxxb> mList = mCjkhjlService.getOneBfrjByZt(uuid);
		if (mList == null || mList.size() == 0){
			return null;
		}
		
		Gson mGson = GsonUtil.getGson();
		
		String str = mGson.toJson(mList);
		
		return str;
	}
	



	@Override
	public void deleteData(String wybs) {
		// TODO Auto-generated method stub
		showMessage(getResources().getString(R.string.param116));
		init();
		mAdapter.notifyDataSetChanged();
	}

	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}
	
}
